import { useState, useCallback, useEffect, useRef } from "react";
import { View, Text, TouchableOpacity, ScrollView, Pressable, ActivityIndicator } from "react-native";
// @ts-ignore
import DialogAndroid from "react-native-dialogs";

import fso from "@/utils/FileOperate/operate";

import CustomIcon from "@/components/CustomIcon";
import globalMethods from "@/GlobalMethodProvider";

import styles from "./styles";

import type { StateType } from "./type";
import config from "@/config";

/** 旧版APP数据 */
const OldAppData = () => {
  const [state, _setState] = useState<StateType>({
    filePath: "",
    content: "",
    loading: true
  });

  // 通用更新状态单个
  const setState = useCallback((field: keyof typeof state, val: any) => {
    _setState(_state => {
      return { ..._state, [field]: val };
    });
  }, []);

  // 通用更新状态(对象)
  const setObjState = useCallback((obj: Partial<typeof state>) => {
    _setState(_state => {
      return { ..._state, ...obj };
    });
  }, []);

  /** 读取文件内容 */
  const readFileContent = useCallback(
    async (url: string) => {
      try {
        const isExists = await fso.exists(url);
        if (isExists) {
          const content = await fso.readFile(url);
          setState("content", content);
        } else {
          setState("content", `${url} 文件不存在`);
        }
      } catch (err) {
        console.log("err: ", err);
        setState("content", err);
      }
    },
    [setState]
  );

  // 初始化
  const init = useCallback(async () => {
    try {
      const exists1 = await fso.exists(fso.oldAppstorageInfoFilePath);
      if (exists1) {
        setObjState({ filePath: fso.oldAppstorageInfoFilePath });
        readFileContent(fso.oldAppstorageInfoFilePath);
      } else {
        const exists2 = await fso.exists(config.oldAppInfo.storageInfoFilePath);
        if (exists2) {
          setObjState({ filePath: config.oldAppInfo.storageInfoFilePath });
          readFileContent(config.oldAppInfo.storageInfoFilePath);
        } else {
          setObjState({
            filePath: fso.oldAppstorageInfoFilePath + "\n" + config.oldAppInfo.storageInfoFilePath,
            content: "文件不存在"
          });
        }
      }
    } catch (err) {
      console.log("err: ", err);
    }
  }, [readFileContent, setObjState]);

  /** 上传文件 */
  const uploadFile = async () => {
    try {
      const oldAppstorageInfoFilePath = state.filePath;
      const isExists = await fso.exists(oldAppstorageInfoFilePath);
      if (isExists) {
        const { action, text } = await DialogAndroid.prompt("上传文件", "输入上传文件的接口地址", {
          defaultValue: `${config.serveUrl.localhostServe}/uploadFile`,
          cancelable: false
        });
        if (action === DialogAndroid.actionPositive) {
          console.log("上传文件: ", oldAppstorageInfoFilePath);
          DialogAndroid.showProgress("文件上传中, 请稍等...", {
            style: DialogAndroid.circular
          });
          const res = await fso
            .uploadFile({
              url: text,
              method: "POST",
              fileName: config.oldAppInfo.storageInfoFileName,
              filePath: oldAppstorageInfoFilePath,
              formDataKey: "file"
            })
            .finally(() => {
              DialogAndroid.dismiss();
            });
          console.log("res: ", res);
          globalMethods.$showMessage({
            type: "toast",
            message: "上传成功"
          });
        }
      } else {
        globalMethods.$showMessage({
          type: "toast",
          message: "文件不存在"
        });
      }
    } catch (err) {
      console.log("err: ", err);
      globalMethods.$showMessage({
        type: "toast",
        message: "文件上传失败"
      });
    }
  };

  /** Loaidng 组件 */
  const LoadingComp = <ActivityIndicator style={styles.loading} animating={state.loading} size={28} color="white" />;

  /** 内容组件 */
  const ContentComp = (
    <ScrollView>
      <Pressable>
        <Text>{state.content}</Text>
      </Pressable>
    </ScrollView>
  );

  useEffect(() => {
    init();
  }, [init]);

  return (
    <View style={styles.container}>
      <View style={styles.contentContainer}>
        <View>
          <View style={styles.contentHeader}>
            <Text>
              文件地址:
              <Text style={styles.contentTitle}>{state.filePath}</Text>
            </Text>

            <TouchableOpacity style={styles.iconContainer} onPress={uploadFile}>
              <CustomIcon name="icon-shangchuan" size={20} />
            </TouchableOpacity>
          </View>
          <View style={styles.division} />
        </View>

        {state.content ? ContentComp : LoadingComp}
      </View>
    </View>
  );
};

export default OldAppData;
